package com.czmini.cztest.common;

import com.alibaba.fastjson.JSONObject;
import com.czmini.cztest.dao.ZcTestUserMapper;
import com.czmini.cztest.dto.ResultDto;
import com.czmini.cztest.dto.TokenDto;
import com.czmini.cztest.dto.jenkins.OperateJenkinsJobDto;
import com.czmini.cztest.entity.ZcTestJenkins;
import com.czmini.cztest.entity.ZcTestUser;
import com.czmini.cztest.util.FileUtil;
import com.czmini.cztest.util.JenkinsUtil;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.Job;
import com.offbytwo.jenkins.model.QueueReference;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.util.StringUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;

/**
 * @ProjectName: cztest
 * @Package: com.czmini.cztest.common
 * @ClassName: JenkinsClient
 * @Author: 还是那个橙子
 * @Description: jenkins 操作
 * @Date: 2022/5/1 23:42
 * @Version: 1.0
 */

@Component
@Slf4j
public class JenkinsClient {
    @Autowired
    private ZcTestUserMapper  zcTestUserMapper;

    @Autowired
    private JenkinsFactory  jenkinsFactory;

    private final String PREFIX_TIPS = "调用Jenkins异常-";


    /**
     * 开启jenkins job
     * @param operateJenkinsJobDto
     * @return
     */
    public ResultDto operateJenkinsJob(OperateJenkinsJobDto operateJenkinsJobDto) throws IOException {

        log.info("operateJenkinsJobDto====="+ JSONObject.toJSONString(operateJenkinsJobDto));
        //获取jenkins操作对象
        ZcTestJenkins zcTestJenkins = operateJenkinsJobDto.getZcTestJenkins();
        //获取token
        TokenDto tokenDto = operateJenkinsJobDto.getTokenDto();
        Map<String, String> params = operateJenkinsJobDto.getParams();

        ZcTestUser queryzcTestUser = new ZcTestUser();
        queryzcTestUser.setId(tokenDto.getUserId());
        // 查询用户信息
        ZcTestUser resultTestUser = zcTestUserMapper.selectOne(queryzcTestUser);

        // 拼接job名称 +job 标识
        String startTestJobName = JenkinsUtil.getStartTestJobName(tokenDto.getUserId());
        String jobSign = JenkinsUtil.getJobSignByName(startTestJobName);

        log.info("=====拼接Job名称====："+ startTestJobName);
        log.info("=====拼接Job标识====："+ jobSign);
        if(StringUtil.isEmpty(jobSign)){
            return ResultDto.fail("Jenkins的Job标识不符合规范");
        }
        //读取classpath下的jenkins.xml配置
        ClassPathResource classPathResource = new ClassPathResource("jenkinsDir/" + jobSign + ".xml");
        InputStream inputStream = classPathResource.getInputStream();

        String jobxml = FileUtil.getText(inputStream);
        log.info("=====jobxml====："+ jobxml);
        if (StringUtil.isEmpty(jobxml)) {
            return ResultDto.fail("job配置信息不能为空");
        }
        //根据user表中的数据决定更新还是新建jo
        String testJobName = resultTestUser.getStartTestJobName();

        if(StringUtil.isEmpty(testJobName)) {
            log.info("=====新建Jenkins执行测试的Job====：");
            //新建job
            createOrUpdateJob(startTestJobName, jobxml, tokenDto.getUserId(), tokenDto.getDefaultJenkinsId(), 1);
            resultTestUser.setStartTestJobName(startTestJobName);
            zcTestUserMapper.updateByPrimaryKeySelective(resultTestUser);
        }else{
            createOrUpdateJob(startTestJobName, jobxml, tokenDto.getUserId(), tokenDto.getDefaultJenkinsId(), 0);
        }
        //获取Jenkinshttpclient构建job
        try{
            JenkinsHttpClient jenkinsHttpClient = jenkinsFactory.getJenkinsHttpClient(tokenDto.getUserId(), tokenDto.getDefaultJenkinsId());
            Job job = getJob(startTestJobName, jenkinsHttpClient, zcTestJenkins.getUrl());
            //有参构建
            build(job, params);
            return ResultDto.success("操作成功");
        }catch (Exception e){
            String tips = PREFIX_TIPS + "操作Jenkins的Job异常"+e.getMessage();
            log.error(tips,e);
            throw new ServiceException(tips);
        }


    }

    /**
     * 构建job - 有参方式
     * @param job
     * @param params
     */
    private QueueReference build(Job job, Map<String, String> params) throws IOException {
      //  QueueReference queueReference = job.build(params);
        QueueReference queueReference=null;
        if(Objects.isNull(params)){
            queueReference=job.build(true);

        }else{
            queueReference=job.build(params,true);
        }
        log.info("=====构建job====："+ JSONObject.toJSONString(queueReference));
        return queueReference;

    }

    /**
     * 获取job
     * @param jobName
     * @param jenkinsHttpClient
     * @param jenkinsBaseUrl
     */
    private Job getJob(String jobName, JenkinsHttpClient jenkinsHttpClient, String jenkinsBaseUrl) {
        ///job/test_aitestbuild/api/json  404  jobName后面需加/，后面改源码
        Job job = new Job(jobName,jenkinsBaseUrl+"job/"+jobName+"/");
        job.setClient(jenkinsHttpClient);
        return job;
    }

    /**
     * 创建更新jenkins job
     * @param
     * @return
     */
    public ResultDto  createOrUpdateJob(String JobName,String jobXml,Integer createUserId,Integer jenkinsId,Integer createJobFlag){
        JenkinsServer jenkinsServer = jenkinsFactory.getJenkinsServer(createUserId, jenkinsId);

        try {
            if(Objects.nonNull(createJobFlag)&&createJobFlag==1){
                //创建job
                jenkinsServer.createJob(JobName,jobXml,true);

            }
            return ResultDto.success("job创建成功");
        }catch (Exception e) {
            String tips = PREFIX_TIPS + "创建或更新Jenkins的Job时异常"+e.getMessage();
            log.error(tips,e);
            throw new ServiceException(tips);

        }
    }



}
